﻿Imports Telerik.Web.UI
Imports System.Data.SqlClient
Imports System.Data
Imports System.IO
Partial Class Payment_PaymentOrderDtl
    Inherits System.Web.UI.Page
    Dim _CommandName As String
    Dim _Command As String
    Dim PaymentOrderHdrObj As New DBPaymentOrderHdrSP
    Dim PaymentOrderHdrDS As New DataSet
    Dim PaymentOrderDtlObj As New DBPaymentOrderDtlSP
    Dim AccountObj As New AccountsSP
    Public strConnection As String = ConfigurationManager.ConnectionStrings("DatabaseConnectionString").ConnectionString.ToString

    Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        Me.Theme = GetGlobalResourceObject("SystemResource", "Theme")
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            Dim _lblPageTitle As Label
            _lblPageTitle = Me.Master.FindControl("lblPageTitle")
            _lblPageTitle.Text = GetLocalResourceObject("PageTitle")
            rdpOrderDate.DbSelectedDate = DateTime.Now()
            rtbTransYear.Text = Year(Now()).ToString()

            hdnPayOrdID.Value = Request.QueryString("PayOrdID").ToString

            If hdnPayOrdID.Value <> "" Then
                FillPaymentOrderDtl()
            Else
                hdnPayOrdID.Value = "-1"
                rdpOrderDate.DbSelectedDate = Now    'Default Document Date is Today
                rtbTransYear.Text = Year(Now()).ToString()         'Default Year is the Current Year
            End If
            'rbtnCancel.Attributes.Add("onClick", "javascript:history.back(); return false;")

        End If
    End Sub



#Region "Attachments"
    Private Sub UploadAttachments()

        Dim FileUpload As RadAsyncUpload = AsyncUploadVoucher
        lblUploadError.Visible = False
        If Not (FileUpload.UploadedFiles.Count > 0) Then
            Return
        End If

        For i As Integer = 0 To FileUpload.UploadedFiles.Count - 1


            Dim fs As System.IO.Stream = FileUpload.UploadedFiles(i).InputStream

            Dim imageBytes As [Byte]() = New [Byte](fs.Length - 1) {}
            fs.Read(imageBytes, 0, CInt(fs.Length))
            fs.Close()

            Dim strQuery As [String]

            'insert the file into database
            strQuery = "insert into tblFiles([Voucher_IDC], [Voucher_IDN],[Name], [ContentType], [Data]) values (@Voucher_IDC, @Voucher_IDN,@Name, @ContentType, @Data)"
            Dim cmd As New SqlCommand(strQuery)
            cmd.Parameters.AddWithValue("@Voucher_IDC", "PO")
            cmd.Parameters.AddWithValue("@Voucher_IDN", hdnPayOrdID.Value.ToString())
            cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = FileUpload.UploadedFiles(i).GetName()

            'Make sure we are dealing with a Compatible File Format Like JPG or GIF file
            Dim extension As String = System.IO.Path.GetExtension(FileUpload.UploadedFiles(i).GetName()).ToLower()
            Dim MIMEType As String = Nothing
            Select Case extension
                Case ".gif"
                    MIMEType = "image/gif"
                    Exit Select
                Case ".jpg", ".jpeg", ".jpe"
                    MIMEType = "image/jpeg"
                    Exit Select
                Case ".png"
                    MIMEType = "image/png"
                    Exit Select
                Case ".bmp"
                    MIMEType = "image/bmp"
                    Exit Select
                Case ".txt"
                    MIMEType = "application/txt"
                    Exit Select
                Case ".pdf"
                    MIMEType = "application/pdf"
                    Exit Select
                Case ".doc"
                    MIMEType = "application/msword"
                    Exit Select
                Case ".xls"
                    MIMEType = "application/msexcel"
                    Exit Select
                Case ".docx"
                    MIMEType = "application/vnd.ms-word"
                    Exit Select
                Case ".xlsx"
                    MIMEType = "application/vnd.ms-excel"
                    Exit Select
                Case Else
                    '   Invalid file type uploaded

                    lblUploadError.Visible = True
                    Return
            End Select

            cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = MIMEType
            cmd.Parameters.Add("@Data", SqlDbType.VarBinary).Value = imageBytes
            ' bytes;
            InsertUpdateData(cmd)

        Next

    End Sub

    Private Function InsertUpdateData(ByVal cmd As SqlCommand) As [Boolean]
        Dim con As New SqlConnection(strConnection)
        cmd.CommandType = CommandType.Text
        cmd.Connection = con
        Try
            con.Open()
            cmd.ExecuteNonQuery()
            Return True
        Catch ex As Exception
            Response.Write(ex.Message)
            Return False
        Finally
            con.Close()
            con.Dispose()
        End Try
    End Function


#End Region


    Sub SaveControls()
        hdnPayOrdID.Value = PaymentOrderHdrObj.QueryDatabase(DBParentStoredProcedureClass.SqlQueryType.ExecuteScalar, "SavePaymentOrderHdr", _
                                                      hdnPayOrdID.Value, rtbPayOrderNo.Text, rtbTransYear.Text, rdpOrderDate.DbSelectedDate, , rcbMainCostCenter.SelectedValue, _
                                                      rcbCostCenter.SelectedValue, rcbPayMeth.SelectedValue, rcbSupplier.SelectedValue, rtbRemarks.Text, , Session("UserName").ToString(), Now)
        SaveDtl()
        UploadAttachments()
    End Sub

    Protected Sub SaveDtl()
        Dim regDate As Date = Date.Now()
        Dim strDate As String = regDate.ToString("ddMMMyyyy")

        For counter = 0 To rgPaymentOrderDtl.Items.Count - 1
            PaymentOrderDtlObj.QueryDatabase(DBParentStoredProcedureClass.SqlQueryType.ExecuteNonQuery, "SavePaymentOrderDtl", rgPaymentOrderDtl.Items(counter)("ID").Text, _
            hdnPayOrdID.Value, _
            IIf(rgPaymentOrderDtl.Items(counter)("LPOYear").Text = "&nbsp;", "", rgPaymentOrderDtl.Items(counter)("LPOYear").Text), _
            IIf(rgPaymentOrderDtl.Items(counter)("LPONo").Text = "&nbsp;", "", rgPaymentOrderDtl.Items(counter)("LPONo").Text), _
             IIf(rgPaymentOrderDtl.Items(counter)("ProgramNo").Text = "&nbsp;", "", rgPaymentOrderDtl.Items(counter)("ProgramNo").Text), _
             IIf(rgPaymentOrderDtl.Items(counter)("ProjectNo").Text = "&nbsp;", "", rgPaymentOrderDtl.Items(counter)("ProjectNo").Text), _
             IIf(rgPaymentOrderDtl.Items(counter)("AccountNo").Text = "&nbsp;", "", rgPaymentOrderDtl.Items(counter)("AccountNo").Text), _
             IIf(rgPaymentOrderDtl.Items(counter)("Amount").Text = "&nbsp;", "", rgPaymentOrderDtl.Items(counter)("Amount").Text), _
             IIf(rgPaymentOrderDtl.Items(counter)("Remarks").Text = "&nbsp;", "", rgPaymentOrderDtl.Items(counter)("Remarks").Text), _
            CType(rgPaymentOrderDtl.Items(counter)("RecordStatus").Controls(0), HyperLink).Text, _
            Session("UserName").ToString(), Now)
        Next
    End Sub



    Protected Sub FillPaymentOrderDtl()
        PaymentOrderHdrDS = PaymentOrderHdrObj.QueryDatabase(DBParentStoredProcedureClass.SqlQueryType.FillDataset, "RtvPaymentOrderHdrByPayOrdID", hdnPayOrdID.Value)
        If PaymentOrderHdrDS IsNot Nothing Then
            If PaymentOrderHdrDS.Tables(0).Rows.Count > 0 Then

                rtbTransYear.Text = PaymentOrderHdrDS.Tables(0).Rows(0).Item("TransYear").ToString()
                rtbPayOrderNo.Text = PaymentOrderHdrDS.Tables(0).Rows(0).Item("PayOrderNo").ToString()
                rdpOrderDate.DbSelectedDate = PaymentOrderHdrDS.Tables(0).Rows(0).Item("PayOrdDate").ToString()
                rcbMainCostCenter.DataBind()
                rcbMainCostCenter.SelectedValue = PaymentOrderHdrDS.Tables(0).Rows(0).Item("MainCostCenter").ToString()
                rcbCostCenter.DataBind()
                rcbCostCenter.SelectedValue = PaymentOrderHdrDS.Tables(0).Rows(0).Item("CostCenter").ToString()
                rcbPayMeth.DataBind()
                rcbPayMeth.SelectedValue = PaymentOrderHdrDS.Tables(0).Rows(0).Item("PayMeth").ToString()
                rcbSupplier.DataBind()
                rcbSupplier.SelectedValue = PaymentOrderHdrDS.Tables(0).Rows(0).Item("SupplierID").ToString()
                rtbRemarks.Text = PaymentOrderHdrDS.Tables(0).Rows(0).Item("Remarks").ToString()
                hdnRecordStatus.Value = PaymentOrderHdrDS.Tables(0).Rows(0).Item("RecordStatus").ToString()


                If hdnRecordStatus.Value = "2" Then 'Voucher is exported so fields disabled
                    rtbTransYear.Enabled = False
                End If
            End If
        End If
    End Sub


    Protected Sub rbtnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles rbtnSave.Click

        SaveControls()
        CleanTemp() ' This Function is to Clean The Temporary Files Stored by RadAsyncUpload in App_Data\RadUploadTemp
        RadAjaxManager1.ResponseScripts.Add("radalert('Information Saved Successfully !', 270, 100);")

    End Sub

    Protected Sub rbtnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles rbtnCancel.Click
        Response.Redirect("~/PaymentOrderHdr.aspx")
    End Sub

    Sub CleanTemp()
        Dim dir As New DirectoryInfo(Server.MapPath("~\App_Data\RadUploadTemp"))
        Dim file As IO.FileInfo() = dir.GetFiles()
        For i = 0 To file.Length - 1
            file(i).Delete()
        Next
    End Sub
    Protected Sub rgPaymentOrderDtl_ItemCommand(ByVal source As Object, ByVal e As GridCommandEventArgs) Handles rgPaymentOrderDtl.ItemCommand
        _CommandName = e.CommandName
    End Sub

    Protected Sub rgPaymentOrderDtl_ItemDataBound(sender As Object, e As Telerik.Web.UI.GridItemEventArgs) Handles rgPaymentOrderDtl.ItemDataBound
        If (TypeOf e.Item Is GridEditFormItem AndAlso e.Item.IsInEditMode) And _CommandName <> "InitInsert" Then
            'If (TypeOf e.Item Is GridEditFormItem AndAlso e.Item.IsInEditMode) Then

            Dim editFormItem As GridEditFormItem = CType(e.Item, GridEditFormItem)
            Dim parentItem As GridDataItem = editFormItem.ParentItem

            Dim box As RadComboBox = CType(editFormItem.FindControl("WUCAcc").FindControl("rcbv"), RadComboBox)
            box.SelectedValue = parentItem("AccountNo").Text
            Dim box1 As RadComboBox = CType(editFormItem.FindControl("WUCAcc").FindControl("rcbd"), RadComboBox)
            box1.SelectedValue = parentItem("AccountNo").Text
        End If
    End Sub

    Protected Sub rbtnDelete_Click(sender As Object, e As System.EventArgs) Handles rbtnDelete.Click
        DeleteRecord()
    End Sub
    Sub DeleteRecord()
        Try
            PaymentOrderDtlObj.QueryDatabase(DBParentStoredProcedureClass.SqlQueryType.ExecuteNonQuery, "DeletePaymentOrderDtl", , hdnPayOrdID.Value)
            PaymentOrderHdrObj.QueryDatabase(DBParentStoredProcedureClass.SqlQueryType.ExecuteNonQuery, "DeletePaymentOrderHdr", hdnPayOrdID.Value)
            Response.Redirect("~/PaymentOrderHdr.aspx")

        Catch ex As Exception
            Response.Write(ex.Message)
        Finally
        End Try
    End Sub
End Class

